package cn.zhangxin.newyear.system.department.service.impl;

import cn.zhangxin.newyear.base.query.BaseQuery;
import cn.zhangxin.newyear.system.department.domain.Department;
import cn.zhangxin.newyear.system.department.mapper.DepartmentMapper;
import cn.zhangxin.newyear.system.department.service.IDepartmentService;
import cn.zhangxin.newyear.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zx
 * @since 2023-01-15
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> getTree() {
        //1.查询全部
        List<Department> deps = departmentMapper.findAll();

        //3.找儿子
        for (Department dep : deps){
            if(dep.getParentId()!=null){
                for (Department parent : deps) {
                    if (dep.getParentId() == parent.getId()){
                        parent.getChildren().add(dep);
                        break;
                    }
                }
            }
        }

        //2.找顶级
        List<Department> firstTree = deps.stream()
                //filter过滤器
                .filter(department -> department.getParentId() == null)
                .collect(Collectors.toList());//转为list
        return firstTree;
    }

    @Override
    @Transactional
    public void add(Department department) {
        //先添加数据
        departmentMapper.add(department);
        buildDirPath(department);
        //修改数据
        departmentMapper.update(department);
    }

    //设置父路径 公共的代码
    private void buildDirPath(Department department){
        Long id = department.getId();
        if (department.getParentId()==null){
            //拼接dirpath
            department.setDirPath("/"+id);
        }else {
            Department byParent1 = departmentMapper.findByParent(department.getParentId());
            String dirPath = byParent1.getDirPath();
            department.setDirPath(dirPath+"/"+id);
        }
    }
    //批量新增
    public void batchAdd(List<Department> depts){
        departmentMapper.batchAdd(depts);
    }

}
